package com.weizhi.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.UserDto;
import com.weizhi.server.entity.User;
import com.weizhi.server.mapper.UserMapper;
import com.weizhi.server.service.UserService;
import com.weizhi.server.util.PropertyCopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Override
    public PageInfo list(JSONObject param) {
        PageHelper.startPage(param.getInteger("pageIndex"), param.getInteger("pageSize"));
        List<User> userList = userMapper.list();
        PageInfo pageInfo = new PageInfo(userList);
        List<UserDto> userDtoList = PropertyCopyUtil.copyList(userList, UserDto.class);
        pageInfo.setList(userDtoList);
        return pageInfo;
    }

    @Override
    public List<UserDto> all() {
        List<User> userList = userMapper.list();
        return PropertyCopyUtil.copyList(userList, UserDto.class);
    }

    @Override
    public UserDto login(UserDto userDto) {
        User userDb = userMapper.selectByUsername(userDto.getUsername());
        if(userDb == null){ // 用户名不存在
            logger.info("用户名不存在, {}", userDto.getUsername());
            throw new RuntimeException("用户名或密码不正确");
        }else{
            if(userDb.getPassword().equals(userDto.getPassword())){ // 登录成功
                logger.info("用户登录成功, {}", userDb);
                return PropertyCopyUtil.copy(userDb, UserDto.class);
            }else{ //密码不正确
                logger.info("密码错误, 用户密码:{}, 登录密码:{}", userDb.getUsername(), userDto.getPassword());
                throw new RuntimeException("用户名或密码不正确");
            }
        }
    }

    @Override
    public void save(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        if(user.getId() == null){
            userMapper.insertSelective(user);
        }else{
            userMapper.updateByPrimaryKeySelective(user);
        }

    }


    @Override
    public void editPassword(UserDto userDto) {
        User user = new User();
        user.setId(userDto.getId());
        user.setPassword(userDto.getPassword());
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }
}
